//
//  UploadImage.m
//  YuErmuYing
//
//  Created by Tiancheng on 16/9/1.
//  Copyright © 2016年 Tiancheng. All rights reserved.
//

#import "UploadImage.h"
#import "AFNetworking.h"

@implementation UploadImage
//上传单张图片
-(void) uploadImage:(UIImage *) image Parameter:(NSDictionary *)parameter FileName:(NSString *)fileName MimeType:(NSString *)mimetype UrlStr:(NSString *)urlStr;
{

    NSURLSessionConfiguration * conf = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:conf];
    NSData * imageData = UIImageJPEGRepresentation(image, 1);
    //申明请求的数据是json类型
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    //如果报接受类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager POST:urlStr parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 上传图片，以文件流的格式
        [formData appendPartWithFileData:imageData name:@"image" fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSDictionary * dic = responseObject[@"data"];
        NSLog(@"%@",dic);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

}

/**
 *  上传带图片的内容，允许多张图片上传（URL）POST
 *
 *  @param url                 网络请求地址
 *  @param images              要上传的图片数组（注意数组内容需是图片）
 *  @param parameter           图片数组对应的参数
 *  @param parameters          其他参数字典
 *  @param ratio               图片的压缩比例（0.0~1.0之间）
 *  @param succeedBlock        成功的回调
 *  @param failedBlock         失败的回调
 *  @param uploadProgressBlock 上传进度的回调
 */
//另一种方法上传(单张图片)

- (NSURLSessionUploadTask*)uploadTaskWithImage:(UIImage*)image URLString:(NSString *)urlString Parameters:(NSDictionary*)parameters completion:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionBlock;
{
    // 构造 NSURLRequest
    NSError* error = NULL;
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSData* imageData = UIImageJPEGRepresentation(image, 1.0);
        [formData appendPartWithFileData:imageData name:@"image" fileName:@"image" mimeType:@"image/png"];
    } error:&error];
    // 可在此处配置验证信息
    // 将 NSURLRequest 与 completionBlock 包装为 NSURLSessionUploadTask
    NSURLSessionConfiguration * conf = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:conf];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
    } completionHandler:completionBlock];
    return uploadTask;
}
//
-(void)uploadTaskWithMoreImages:(NSMutableArray *)imageArray URLString:(NSString *)urlString Parameters:(NSDictionary*)parameters;
{
    dispatch_group_t group = dispatch_group_create();
    
    for (NSInteger i = 0; i < imageArray.count; i++)
    {
        
        dispatch_group_enter(group);
      NSURLSessionUploadTask* uploadTask=[self uploadTaskWithImage:imageArray[i] URLString:urlString Parameters:parameters completion:^(NSURLResponse *response, id responseObject, NSError *error)
        {

            if (error) {
                NSLog(@"第 %d 张图片上传失败:%@", (int)i + 1, error);
                dispatch_group_leave(group);
            } else {
//                NSLog(@"第 %d 张图片上传成功:%@", (int)i + 1, responseObject);
                @synchronized (imageArray) { // NSMutableArray 是线程不安全的，所以加个同步锁
                    imageArray[i] = responseObject;
                    NSLog(@"第 %d 张图片上传成功:%@", (int)i + 1, responseObject);

                }
                dispatch_group_leave(group);
            }
        }];
        [uploadTask resume];
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"上传完成!");
        for (id response in imageArray)
        {
            NSLog(@"%@", response);
        }
    });
}

-(void)uploadMoreImages:(NSArray *)imageArray Parameter:(NSDictionary *)parameter FileName:(NSString *)fileName MimeType:(NSString *)mimetype UrlStr:(NSString *)urlStr;
{
//    dispatch_group_t group = dispatch_group_create();

    for (NSInteger i = 0; i < imageArray.count; i++)
    {
//        dispatch_group_enter(group);
        UIImage *image=imageArray[i];
        NSURLSessionConfiguration * conf = [NSURLSessionConfiguration defaultSessionConfiguration];
        AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:conf];
        NSData * imageData = UIImageJPEGRepresentation(image, 1);
        //申明请求的数据是json类型
        manager.requestSerializer=[AFJSONRequestSerializer serializer];
        //如果报接受类型不一致请替换一致text/html或别的
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
        [manager POST:urlStr parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            // 上传图片，以文件流的格式
            [formData appendPartWithFileData:imageData name:@"image" fileName:fileName mimeType:@"image/png"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@",responseObject);
            NSDictionary * dic = responseObject[@"data"];
            NSLog(@"%@",dic);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
//    dispatch_group_leave(group);
}

//上传多张图片的接口
-(void) uploadImageArray:(NSArray *) imageArray Parameter:(NSDictionary *)parameter ParamName:(NSString *)paramName FileName:(NSString *)fileName MimeType:(NSString *)mimetype UrlStr:(NSString *)urlStr
{
    NSURLSessionConfiguration * conf = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:conf];
    for (UIImage * image in imageArray) {
        NSData * imageData = UIImageJPEGRepresentation(image, 1);
        //    NSData  * imageData = [[NSData alloc]initWithBytes:(__bridge const void * _Nullable)(imageArray) length:3];
        //申明请求的数据是json类型
        manager.requestSerializer=[AFJSONRequestSerializer serializer];
        //如果报接受类型不一致请替换一致text/html或别的
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
        [manager POST:urlStr parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            // 上传图片，以文件流的格式
            [formData appendPartWithFileData:imageData name:paramName fileName:fileName mimeType:mimetype];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@",responseObject);
            NSDictionary * dic = responseObject[@"data"];
            NSLog(@"%@",dic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}



@end
